package com.study.lxy.springcloud.common.utils;

import com.study.lxy.springcloud.common.constance.CommonRespEnum;
import com.study.lxy.springcloud.common.exception.BusiException;
import org.bouncycastle.util.encoders.Hex;

import java.security.MessageDigest;

public class PasswordUtil {

    private static String CHAR_SET = "UTF-8";
    private static String SHA_256 = "SHA-256";
    private static String SHA_1 = "SHA-1";
    private static String MD5 = "MD5";

    /**
     * 使用hash + salt算法，生成hash之后的密码，默认使用SHA-256加密算法
     * @param password
     * @param salt
     * @return
     */
    public static String getHashWithSaltPassword(String password,String salt) {
        return getHashWithSaltPassword(password,salt,SHA_256);
    }

    /**
     * 使用hash + salt算法，生成hash之后的密码，可选加密算法
     * @param password
     * @param salt
     * @param secType
     * @return
     */
    public static String getHashWithSaltPassword(String password,String salt,String secType){
        return passwordHash(password + salt,secType);
    }

    private static String passwordHash(String str,String secType){
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(secType);
            byte[] bs = messageDigest.digest(str.getBytes(CHAR_SET));
            return Hex.toHexString(bs);
        } catch (Exception e){
            throw new BusiException(CommonRespEnum.PW_MD5_ERROR);
        }
    }

    /**
     * 验证密码-默认使用SHA-256加密
     * @param password
     * @param salt
     * @param hashedPassword
     * @return
     */
    public static boolean verifyPassword(String password,String salt,String hashedPassword){
        return verifyPassword(password,salt,SHA_256,hashedPassword);
    }

    /**
     * 验证密码-可选的加密方法
     * @param password
     * @param salt
     * @param secType
     * @param hashedPassword
     * @return
     */
    public static boolean verifyPassword(String password,String salt,String secType,String hashedPassword){
        String inputHashed = getHashWithSaltPassword(password,salt,secType);
        if(hashedPassword.equals(inputHashed)){
            return true;
        }
        return false;
    }
}
